package com.clothing.customization.service.impl;

import com.clothing.customization.dto.AuthResponse;
import com.clothing.customization.dto.LoginRequest;
import com.clothing.customization.dto.RegisterRequest;
import com.clothing.customization.entity.User;
import com.clothing.customization.enums.Status;
import com.clothing.customization.repository.UserRepository;
import com.clothing.customization.service.UserService;
import com.clothing.customization.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

/**
 * 用户服务实现类
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;
    
    /**
     * 用户注册
     * @param request 注册请求
     * @return 注册用户
     */
    @Override
    @Transactional
    public User register(RegisterRequest request) {
        // 验证两次密码是否一致
        if (!Objects.equals(request.getPassword(), request.getConfirmPassword())) {
            throw new IllegalArgumentException("两次输入的密码不一致");
        }
        
        // 验证用户名是否已存在
        if (userRepository.existsByUsername(request.getUsername())) {
            throw new IllegalArgumentException("用户名已存在");
        }
        
        // 验证邮箱是否已存在
        if (request.getEmail() != null && userRepository.existsByEmail(request.getEmail())) {
            throw new IllegalArgumentException("邮箱已被注册");
        }
        
        // 验证手机号是否已存在
        if (request.getPhone() != null && userRepository.existsByPhone(request.getPhone())) {
            throw new IllegalArgumentException("手机号已被注册");
        }
        
        // 创建用户对象
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setRealName(request.getRealName());
        user.setEmail(request.getEmail());
        user.setPhone(request.getPhone());
        user.setAddress(request.getAddress());
        user.setRole("user"); // 普通用户角色
        user.setStatus(Status.User.ENABLED); // 默认状态为活跃
        user.setRegisterTime(new Date());
        
        // 保存用户
        return userRepository.save(user);
    }
    
    /**
     * 用户登录
     * @param request 登录请求
     * @return 认证响应
     */
    @Override
    public AuthResponse login(LoginRequest request) {
        // 根据用户名查找用户
        User user = userRepository.findByUsername(request.getUsername())
                .orElseThrow(() -> new BadCredentialsException("用户名或密码错误"));
        
        // 如果指定了角色，验证角色是否匹配
        if (request.getRole() != null && !request.getRole().isEmpty() 
                && !user.getRole().equals(request.getRole())) {
            throw new BadCredentialsException("用户角色不匹配");
        }
        
        // 验证密码
        if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        
        // 验证账号状态
        if (user.getStatus() != Status.User.ENABLED) {
            throw new BadCredentialsException("账号已被禁用");
        }
        
        // 更新最后登录时间
        user.setLastLoginTime(new Date());
        userRepository.save(user);
        
        // 生成JWT token
        String token = jwtUtil.generateToken(user);
        
        // 构建认证响应
        return AuthResponse.builder()
                .token(token)
                .username(user.getUsername())
                .realName(user.getRealName())
                .role(user.getRole())
                .avatar(user.getAvatar())
                .userId(user.getId())
                .build();
    }
    
    /**
     * 根据用户名查找用户
     * @param username 用户名
     * @return 用户对象
     */
    @Override
    public User getUserByUsername(String username) {
        return userRepository.findByUsername(username)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在"));
    }
    
    /**
     * 根据ID查找用户
     * @param id 用户ID
     * @return 用户对象
     */
    @Override
    public User getUserById(Long id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在"));
    }
    
    /**
     * 检查用户名是否已存在
     * @param username 用户名
     * @return 是否存在
     */
    @Override
    public boolean isUsernameExists(String username) {
        return userRepository.existsByUsername(username);
    }
} 